package se.wobbia.android.net;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

public class HttpProxyMonitored extends HttpProxy {
	private static final int CONNECTION_TIMEOUT = 15000000;
	private static final String TAG = "HttpProxyMonitored";
	private Context context;

	public HttpProxyMonitored(String url, Context context) {
		super(url);
		this.context = context;
	}

	@Override
	public JSONObject run(Bundle bundle) {
		JSONObject json = new JSONObject();
		HttpClient httpclient = new DefaultHttpClient();
		HttpParams http_params = httpclient.getParams();
		http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
				HttpVersion.HTTP_1_1);
		HttpConnectionParams.setConnectionTimeout(http_params,
				CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(http_params, CONNECTION_TIMEOUT);

		String fileName = (String) bundle.get("file");
		File file = new File(fileName);
		HttpPost httppost = new HttpPost(url);
		MultipartEntityMonitored mp_entity = new MultipartEntityMonitored(
				context, "test");

		mp_entity.addPart("filename", new FileBody(file));
		httppost.setEntity(mp_entity);

		HttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
			Log.d(TAG, "Status" + response.getStatusLine().getStatusCode());
			HttpEntity resEntity = response.getEntity();
			Log.d(TAG,EntityUtils.toString(resEntity));
			if (resEntity != null) {
				resEntity.consumeContent();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return json;
	}

}
